import {StyleSheet, View, TouchableOpacity, Dimensions} from 'react-native';
import {ObserverText} from './ObserverText';
import React, {ReactElement, useEffect, useState} from 'react';
import {dpw10, dpw12, dpw24, dpw340, dpw92} from '../constants';

const heightScreen = Dimensions.get('screen').height;

interface TabsProps {
  titles: any;
  children: ReactElement;
  isFixed?: boolean;
  pId?: number;
}

export const TabsH = (props: TabsProps) => {
  const {titles, children, isFixed, pId} = props;
  const [idx, setIdx] = useState<number>();

  useEffect(() => {
    if (typeof pId === 'number') {
      setIdx(pId);
    } else if (typeof titles[0]?.Id === 'number') {
      setIdx(titles[0]?.Id);
    }
  }, [titles[0]?.Id, pId]);

  const onPress = (id: number) => {
    if (idx !== id) {
      setIdx(id);
    }
  };

  return (
    <View style={styles.box}>
      {isFixed ? (
        <View style={{width: dpw92}} />
      ) : (
        <View style={styles.titles}>
          {Array.isArray(titles)
            ? titles.map((it, i) => (
                <TouchableOpacity
                  key={it.Id || i}
                  onPress={() => onPress(it.Id)}
                  style={styles.title}>
                  <ObserverText
                    isActive={idx === it.Id}
                    tKey={`${it.Title || ''}`.trim()}
                    type="tab-title-h"
                  />
                </TouchableOpacity>
              ))
            : null}
        </View>
      )}
      <View style={styles.contentbox}>
        {React.cloneElement(children, {
          id: idx,
          title: (titles || []).find((it: any) => it.Id === idx)?.Title,
        })}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  box: {
    width: '100%',
    minHeight: heightScreen - dpw340,
    flexDirection: 'row',
  },
  titles: {
    flexDirection: 'column',
  },
  title: {
    marginBottom: dpw10,
    borderTopRightRadius: dpw24,
    borderBottomRightRadius: dpw24,
    overflow: 'hidden',
  },
  contentbox: {
    flex: 1,
    paddingHorizontal: dpw12,
  },
});
